/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.yunyichina.provider.framework.annotation.validate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * Validate the @ValidateBeforeThan annotation
 *
 * @author jiangtch
 */
public class ValidateNotLaterThanHandler implements Handler {

    private static final Logger logger = LoggerFactory.getLogger(ValidateNotLaterThanHandler.class);

    public void validate(AnnotationValidable validatedObj, Field field)
            throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "validate()");
        }
        if (field.isAnnotationPresent(ValidateNotLaterThan.class)) {
            checkTime(validatedObj, field);
        }
    }

    /**
     * validate if the start time is early than the end time
     *
     * @param filter validated object
     * @param field  validated field or property
     * @throws ValidateException
     */
    private void checkTime(AnnotationValidable filter, Field field)
            throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "checkTime()");
        }
        ValidateNotLaterThan annotation = field
                .getAnnotation(ValidateNotLaterThan.class);
        String sTime = field.getName();
        String eTime = annotation.laterTime();
        Date startTime;
        Date endTime;
        try {
            startTime = (Date) GetFiledValue.getField(filter, sTime);
            endTime = (Date) GetFiledValue.getField(filter, eTime);
        } catch (Exception ex) {
            logger.error("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
            throw new ValidateException("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
        }
        if (startTime != null && endTime != null) {
            if (startTime.after(endTime)) {
                logger.warn("字段：" + field.getName() + " 校验失败,开始时间为:" + startTime + ",结束时间为:" + endTime);
                throw new ValidateException("字段：" + field.getName() + " 校验失败,开始时间为:" + startTime + ",结束时间为:" + endTime);
            }
        } else {
            logger.warn("字段：" + field.getName() + "校验失败.开始时间或结束时间是空值,开始时间是:" + startTime + ", 结束时间是:" + endTime);
            throw new ValidateException("字段：" + field.getName() + "校验失败.开始时间或结束时间是空值,开始时间是:" + startTime + ", 结束时间是:" + endTime);
        }
    }

}
